# ========= 导入基础模块 ============
from resources_base.module_base.importbase import *
from resources_base.module_base.basetools import md5
# ========= 导入数据的类 ============
from userweb.models import Account, Roles


def index(request):
    """展示登陆账号的页面"""
    return render(request, 'user/account.html')


def list_values(request):
    """获取所有登陆账号"""
    # 获取前台传递的信息
    page = int(request.POST.get('page'))
    limit = int(request.POST.get('limit'))
    q_str = request.POST.get('q_str')
    # 获取符合条件的账号
    account_objs = list(Account.objects.filter(Q(loginid__icontains=q_str) | Q(name__icontains=q_str)).values())
    # 遍历-优化时间展示
    for index, value in enumerate(account_objs):
        # 添加角色信息  --- 要被xm-select选中 [{name:  , value:  },{name:  , value:  },]
        roles_objs = list(Roles.objects.filter(account__loginid=value.get('loginid')).values('id','name'))
        # 定义集合
        select_roles = []
        # 遍历
        for item in roles_objs:
            select_roles.append({'name': item.get('name'), 'value': item.get('id')})
        # 携带到集合中
        account_objs[index]['select_roles'] = select_roles

        # 判断是否有上次登陆时间
        if value.get('last_login'):
            account_objs[index]['last_login'] = value.get('last_login').strftime('%Y-%m-%d %H:%M:%S')
        else:
            account_objs[index]['last_login'] = "尚未登陆"

        # 判断是否有创建时间
        if value.get('create_time'):
            account_objs[index]['create_time'] = value.get('create_time').strftime('%Y-%m-%d %H:%M:%S')

        # 判断是否有修改时间
        if value.get('edit_time'):
            account_objs[index]['edit_time'] = value.get('edit_time').strftime('%Y-%m-%d %H:%M:%S')
        else:
            account_objs[index]['edit_time'] = "尚未修改"

    # 分页
    one_page_data = account_objs[(page - 1) * limit:page * limit]
    # 返回
    return JsonResponse({'code': 0, 'count': len(account_objs), 'data': one_page_data})


def add_value(request):
    """添加登陆账号"""
    # 接收前台传递的数据
    rec = request.POST
    # 获取角色的字符串
    roles_str = rec.get('roles')
    # 获取用户状态
    status = 0
    if request.POST.get('status'):
        status = 1
    # 判断账号是否存在！
    is_exists = Account.objects.filter(loginid=rec.get('loginid')).exists()
    if is_exists:
        return JsonResponse({'status': False, 'error': '账号已存在！'})

    try:
        # ====== 1. 添加账号 ============
        Account.objects.create(loginid=rec.get('loginid'), name=rec.get('name'), loginpwd=md5(rec.get('loginpwd')),
                               status=status, department=rec.get('department'), position=rec.get('position'),
                               mobile=rec.get('mobile'), email=rec.get('email'),
                               create_time=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                               )
        # ===== 2. 添加账号和组的映射关系 =========
        if roles_str:
            # 1） 获取刚才添加的账号对象
            account_obj = Account.objects.filter(loginid=rec.get('loginid')).first()
            # 2） 获取所有的角色
            roles_str_list = roles_str.split(",") # 1,2
            # 遍历
            for item in roles_str_list:
                # 获取组的对象
                roles_obj = Roles.objects.filter(id=item).first()
                # 添加映射关系
                roles_obj.account.add(account_obj)

        return JsonResponse({'status': True})
    except Exception as e:
        return JsonResponse({'status': False, 'error': '添加账号提交到数据库出现异常，具体原因：' + str(e)})


def edit_value(request):
    """修改登陆账号"""
    # 接收前台传递的数据
    rec = request.POST
    # 获取用户状态
    status = 0
    if request.POST.get('status'):
        status = 1
    # 开始修改
    try:
        # ==========================1. 修改账号基本信息 ===========================
        # 获取当前操作的对象
        account_obj = Account.objects.filter(loginid=rec.get('loginid')).first()
        # 开始修改
        account_obj.name = rec.get('name')
        account_obj.status = status
        account_obj.department = rec.get('department')
        account_obj.position = rec.get('position')
        account_obj.mobile = rec.get('mobile')
        account_obj.email = rec.get('email')
        account_obj.edit_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        # 保存
        account_obj.save()

        #  ==========================2. 修改角色信息 ===========================
        # 1. 获取当前用户数据库中存储的角色
        db_roles = list(Roles.objects.filter(account__loginid=rec.get('loginid')).values_list('id', flat=True))

        # 2. 获取表单中传递过去的角色
        commit_roles = []
        # 判断提交的角色是否为空
        if rec.get('roles'):
            role_list = rec.get('roles').split(",")
            # 遍历
            for item in role_list:
                commit_roles.append(int(item))

        # 3. 获取要删除的角色关系 --- set集合
        del_roles = list(set(db_roles) - set(commit_roles))
        # 4. 获取要添加的角色关系--- set集合
        add_roles = list(set(commit_roles) - set(db_roles))
        # 5. 开始删除
        for item in del_roles:
            # 实例化roles
            obj_roles = Roles.objects.filter(id=item).first()
            # 删除
            obj_roles.account.remove(account_obj)
        # 6. 开始添加
        for item in add_roles:
            # 实例化roles
            obj_roles = Roles.objects.filter(id=item).first()
            # 删除
            obj_roles.account.add(account_obj)

        # 返回
        return JsonResponse({'status': True})
    except Exception as e:
        return JsonResponse({'status': False, 'error': '编辑账号提交到数据库出现异常，具体原因：' + str(e)})


def del_value(request):
    """删除登陆账号"""
    # 获取传递的loginid
    loginid = request.POST.get('loginid')
    # 开始删除
    try:
        # 开始删除
        Account.objects.filter(loginid=loginid).delete()
        # 返回
        return JsonResponse({'status': True})
    except Exception as e:
        return JsonResponse({'status': False, 'error': '删除账号提交到数据库出现异常，具体原因：' + str(e)})


def change_pwd(request):
    """修改密码"""
    # 接收传递的值
    rec = request.POST
    # 判断旧密码是否正确
    account_obj = Account.objects.filter(loginid=rec.get('ch_loginid'), loginpwd=md5(rec.get('ch_oldPass'))).first()
    # 如果没有，密码错误！
    if not account_obj:
        return JsonResponse({'status':False, 'error': '输入的原密码错误！'})
    # 修改密码
    try:
        # 修改密码
        account_obj.loginpwd = md5(rec.get('ch_newPass'))
        # 保存
        account_obj.save()
        # 返回
        return JsonResponse({'status':True,})
    except Exception as e:
        return JsonResponse({'status': False, 'error': '修改密码提交到数据库出现异常，具体原因：' + str(e)})


def change_account_status(request):
    """修改账号的状态"""
    # 接收传递的值
    loginid = request.POST.get('loginid')
    status = request.POST.get('status')
    # 修改状态
    try:
        # 获取当前的账号
        account_obj = Account.objects.filter(loginid=loginid).first()
        # 修改状态
        account_obj.status = status
        # 保存
        account_obj.save()
        # 返回
        return JsonResponse({'status':True,})
    except Exception as e:
        return JsonResponse({'status': False, 'error': '修改账号状态提交到数据库出现异常，具体原因：' + str(e)})
